//
//  UserAccount.swift
//  weibo
//
//  Created by David on 15/11/25.
//  Copyright © 2015年 DV. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    var access_token:String!
    var uid:String!
//    var expires_i
    var expires_in:NSTimeInterval=0 {
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var expiresDate : NSDate?
        
    
    
    var name:String?
    var avatar_large:String?
    override init() {
        super.init()
    }
     init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    func saveAccount(){
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last?.stringByAppendingString("/account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path!)
    }
    private static var account:UserAccount?
    class func loadAccount()->UserAccount? {
        if account == nil{
            let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/account.plist")
           account = NSKeyedUnarchiver.unarchiveObjectWithFile(path)as?UserAccount
            
        }
        return account
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token")as?String
        uid = aDecoder.decodeObjectForKey("uid")as?String
        name = aDecoder.decodeObjectForKey("name")as?String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as?String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate")as?NSDate
    }
}

